package com.laycoding.layrpc.handler.server;


import com.laycoding.layrpc.common.LayRpcServiceCache;
import com.laycoding.layrpc.common.SpringUtils;
import com.laycoding.layrpc.entity.LayRpcMessage;
import com.laycoding.layrpc.entity.LayRpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@ChannelHandler.Sharable
public class MyRegistryHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().writeAndFlush("hello ~ " + ctx.channel().config().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof String) {
            ctx.channel().writeAndFlush(msg);
        } else {
            LayRpcMessage rpcMessage = (LayRpcMessage) msg;
            String className = rpcMessage.getClassName();
            Object res = "null";
            boolean hasBean = SpringUtils.containsBean(className);
            if (hasBean) {
                Object service = SpringUtils.getBean(className);
                Method method = service.getClass().getMethod(rpcMessage.getMethodName(), rpcMessage.getParams());
                res = method.invoke(service, rpcMessage.getValues());
            }
            if (res instanceof LayRpcResponse) {
                LayRpcResponse layRpcResponse = (LayRpcResponse) res;
                layRpcResponse.setRpcId(rpcMessage.getRpcId());
                ctx.channel().writeAndFlush(layRpcResponse);
            }else {
                ctx.channel().writeAndFlush(res);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
